//ref:https://www.geeksforgeeks.org/dfs-traversal-of-a-tree-using-recursion/
var Node = function (value, children) {
    this.value = value;
    this.children = children ? children : [];
}

function treeDPrinter(root) {
    if (!root) return;
    q = [];
    q.push(root);
    var res = [];
    while (q.length) {
        count = q.length;
        var row = []
        while (count) {
            temp = q.shift();
            row.push(temp.value)
            if (temp.children && temp.children.length) {
                for (child of temp.children) {
                    q.push(child);
                }
            }
            count--;
        }
        res.push(row.join(' '))
    }
    return res.join('\n')
}
var B = new Node('B');
var C = new Node('C');
var A = new Node('A', [B, C])
var E = new Node('E', [A])
var F = new Node('F', [new Node('R'), new Node('J')])

var tree = new Node('D', [E, F, new Node('G')])

console.log(treeDPrinter(tree))